
package uestc.bitman.edxapp.chapter;

import uestc.bitman.edxapp.EdxApp;
import uestc.bitman.edxapp.EdxAppConfigurations;
import uestc.bitman.edxapp.EdxStudentUser;
import uestc.bitman.edxapp.R;
import uestc.bitman.edxapp.courselist.Course;
import uestc.bitman.edxapp.mainui.EdxAppFragment;
import uestc.bitman.edxapp.misc.ChangeEnrollmentAsyncTask;
import uestc.bitman.edxapp.misc.ChangeEnrollmentParameters;
import uestc.bitman.edxapp.player.IXmlToVideoDescriptors;
import uestc.bitman.edxapp.player.VideoDesciptor;
import uestc.bitman.edxapp.player.VideoSelectLlistActivity;
import uestc.bitman.edxapp.player.XmlStringVideoParser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * @category UI fragment of a course
 */
public class CourseChaptersFragment extends EdxAppFragment {

    // Progress bar to show at loading
    private ProgressDialog mProgressDlg;

    private Context mContext;

    private ExpandableListView mChapterView;

    private CourseChaptersAdapter mChapterAdapter;

    private Course mCourse;

    // WebView to show the course info
    private CourseInfoWebView mWebView;

    public CourseChaptersFragment() {

    }

    /**
     * onCreate
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mChapterAdapter = new CourseChaptersAdapter(mContext);
    }

    @Override
    /**
     * @category onCreateView
     */
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // when switch to this page,update the title and disable the press again
        // to exit
        ((Activity) mContext).setTitle(mCourse.getDisplayName());

        setHasOptionsMenu(true);

        View view = initLayout(inflater, container, savedInstanceState);

        initCourseData();

        // show the progress
        mProgressDlg = ProgressDialog.show(mContext, getString(R.string.title_processing),
                getString(R.string.label_content_processing));

        return view;
    }

    /**
     * @category Inflate views
     * @param inflater inflater from onCreateView
     * @param container see inflater
     * @param savedInstanceState see inflater
     * @return the view which inflated
     */
    private View initLayout(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.chapter_fragment, container, false);
        mChapterView = (ExpandableListView) view.findViewById(R.id.course_chapters_listview);
        mChapterView.setOnChildClickListener(new OnSectionClickedListener());
        mChapterView.setAdapter(mChapterAdapter);

        mWebView = (CourseInfoWebView) view.findViewById(R.id.course_info);
        return view;
    }

    /**
     * @category Load data of the sepecified course
     */
    private void initCourseData() {
        // get the current user
        EdxStudentUser studentUser = EdxApp.getEdxAppUser();

        // load the course info
        CourseInfoAsyncTask infoAsyncTask = new CourseInfoAsyncTask();
        infoAsyncTask.execute(mCourse.getTarget());

        // load the chapter list of the course
        ChapterListAsyncTask asyncTask = new ChapterListAsyncTask();
        asyncTask.execute(studentUser);
    }

    /**
     * @param course Pass the data of a course to this Fragment to show
     */
    public void setCourse(Course course) {
        this.mCourse = course;
    }

    /**
     * @author hackeris
     * @category Listener of child(section) clicked
     */
    class OnSectionClickedListener implements OnChildClickListener {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                int childPosition, long id) {
            SectionVideoAsyncTask contentAsyncTask = new SectionVideoAsyncTask();
            contentAsyncTask.execute(groupPosition, childPosition);
            return true;
        }
    }

    /**
     * @author hackeris
     * @category AsyncTask of loading chapters and sections of a specified
     *           course.
     */
    class ChapterListAsyncTask extends AsyncTask<EdxStudentUser, Void, List<CourseChapter>> {

        @Override
        protected List<CourseChapter> doInBackground(EdxStudentUser... params) {
            EdxStudentUser studentUser = params[0];
            return studentUser.getCourseChapters(mCourse.getCourseware());
        }

        @Override
        protected void onPostExecute(List<CourseChapter> chapters) {
            mProgressDlg.dismiss();
            /**
             * If the chapters is null which means failed,return
             */
            if (chapters == null) {
                Toast.makeText(mContext, getString(R.string.label_no_chapters), Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            mChapterAdapter.reloadCourseChapters(chapters);
            mChapterAdapter.notifyDataSetChanged();
        }
    }

    /**
     * @author hackeris Update the course info to the CourseInfoWebView
     */
    class CourseInfoAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... subUrl) {
            EdxStudentUser studentUser = EdxApp.getEdxAppUser();
            return studentUser.getCourseInfoHtml(subUrl[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            if (result == null) {
                return;
            }
            mWebView.loadDataWithBaseURL(
                    EdxAppConfigurations.createRequestUrl(mCourse.getTarget()), result,
                    "text/html", "UTF-8", EdxAppConfigurations.SERVER_DOMAIN);
        }
    }

    /**
     * @author hackeris
     * @category Get the video list from a sepecified section
     */
    class SectionVideoAsyncTask extends AsyncTask<Integer, Void, List<VideoDesciptor>> {

        int group, child;

        @Override
        protected List<VideoDesciptor> doInBackground(Integer... params) {
            EdxStudentUser studentUser = EdxApp.getEdxAppUser();
            group = params[0];
            child = params[1];
            String sectionId = mChapterAdapter.getGroup(params[0]).getSection(params[1]).getUrl();

            IXmlToVideoDescriptors parser = new XmlStringVideoParser(
                    studentUser.getCourseSectionContentXml(sectionId));
            return parser.parseToVideos();
        }

        @Override
        protected void onPostExecute(List<VideoDesciptor> result) {
            int size = result.size();
            if (size > 0) {
                Intent intent = new Intent(getActivity(), VideoSelectLlistActivity.class);
                intent.putParcelableArrayListExtra("videos",
                        (ArrayList<? extends Parcelable>) result);
                intent.putExtra("chapter", mChapterAdapter.getGroup(group).getChapterDisplayName());
                intent.putExtra("course", mCourse.getDisplayName());
                intent.putExtra("section", mChapterAdapter.getGroup(group).getSection(child)
                        .getSectioDisplayName());
                startActivity(intent);

            } else {
                Toast.makeText(mContext, getString(R.string.label_no_video), Toast.LENGTH_SHORT)
                        .show();
            }
            // startFragment(new UnitsTabsFragment(), "units", true);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_course, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        switch (id) {
            case R.id.action_unenroll:
                ChangeEnrollmentParameters parameter = new ChangeEnrollmentParameters() {
                    @Override
                    public void onPostExecute(boolean result) {
                        Toast.makeText(mContext, mContext.getString(R.string.label_ok_unenroll),
                                Toast.LENGTH_SHORT).show();
                    }
                };
                parameter.setAction(EdxAppConfigurations.CHANGE_ENROLLMENT_UNENROLL_ACTION);
                parameter.setCourseId(mCourse.getCourseId());
                ChangeEnrollmentAsyncTask enrollAsyncTask = new ChangeEnrollmentAsyncTask();
                enrollAsyncTask.execute(parameter);
                getActivity().onBackPressed();
                return true;
        }
        return false;
    }

}
